package com.hutu.tree;

import java.util.Arrays;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 *
 * @author hutu
 * @date 2020/12/17 9:54 上午
 */
public class SearchRange {

    public static int[] searchRange(int[] nums, int target) {
        return new int[]{leftBound(nums, target), rightBound(nums, target)};
    }

    public static int leftBound(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                right = mid-1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        if (left==nums.length||nums[left]!=target){
            return -1;
        }
        return left;
    }

    public static int rightBound(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                left = mid+1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        if (right<0||nums[right]!=target){
            return -1;
        }
        return right;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(searchRange(new int[]{1,2,3,4,4,4,5,6},5)));
        System.out.println(Arrays.toString(searchRange(new int[]{},5)));
        System.out.println(Arrays.toString(searchRange(new int[]{5,7,7,8,8,10},6)));
    }

}
